package com.ztx.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // 定义切点，拦截所有方法
    @Pointcut("execution(* com.ztx..*.*(..))")
    public void logAllMethods() {}

    @Around("logAllMethods()")
    public Object logMethodExecution(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        String methodName = proceedingJoinPoint.getSignature().getName();
        String className = proceedingJoinPoint.getTarget().getClass().getSimpleName();
        Object[] arguments = proceedingJoinPoint.getArgs();

        logger.info("Before execution of {} in {}. Arguments: {}", methodName, className, arguments);

        Object result;
        try {
            // 执行目标方法
            result = proceedingJoinPoint.proceed();
        } catch (Exception e) {
            logger.error("Exception occurred during execution of {} in {}", methodName, className, e);
            throw e;
        }

        logger.info("After execution of {} in {}. Result: {}", methodName, className, result);

        return result;
    }

}
